<?php
/*

*    接收微信官方推送的ticket值以及取消授权等操作

*/

namespace app\home\controller;

use app\home\model\Miniprogram;
use think\Db;
use think\Exception;

class Openoauth extends Common

{

    /*

    *    接收微信官方推送的消息（每10分钟1次）

    *    这里需要引入微信官方提供的加解密码示例包

    *    官方文档：https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318479&token=&lang=zh_CN

    *    示例包下载：https://wximg.gtimg.com/shake_tv/mpwiki/cryptoDemo.zip

    */

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub

    }

    public function index()

    {
        $encryptMsg = file_get_contents("php://input");

        require_once '../vendor/php/wxBizMsgCrypt.php';

        $xml_tree = new \DOMDocument();

        $xml_tree->loadXML($encryptMsg);

        $xml_array = $xml_tree->getElementsByTagName("Encrypt");

        $encrypt = $xml_array->item(0)->nodeValue;

        $Prpcrypt = new \Prpcrypt($this->encodingAesKey);

        $postData = $Prpcrypt->decrypt($encrypt, $this->appid);

        $timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']);
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        $msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']);
        $auth_code   = empty($_GET['auth_code']) ? ""    : trim($_GET['auth_code']);
        $xml = '
        $encryptMsg = "'.$encryptMsg.'";
        $timeStamp = "'.$timeStamp.'";
        $nonce = "'.$nonce.'";
        $msg_sign = "'.$msg_sign.'";
        $auth_code = "'.$auth_code.'";
        ';
        file_put_contents('tnm.txt',$xml);
//        $msg = '';
//
//        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
//        if ($errCode == 0) {
//            //print("解密后: " . $msg . "\n");
//            $xml = new \DOMDocument();
//            $xml->loadXML($msg);
//            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
//            $component_verify_ticket = $array_e->item(0)->nodeValue;
//            file_put_contents('ticket1.log', $component_verify_ticket);
//            logResult('msgmsg.log','解密后的component_verify_ticket是：'.$component_verify_ticket);
//
//            echo 'success';
//
//        } else {
//            logResult('error.log','解密后失败：'.$errCode);
//            print($errCode . "\n");
//        }
        if ($postData[0] != 0) {

            return $postData[0];

        } else {

            $msg = $postData[1];

            $xml = new \DOMDocument();

            $xml->loadXML($msg);

            $array_a = $xml->getElementsByTagName("InfoType");

            $infoType = $array_a->item(0)->nodeValue;

            if ($infoType == "unauthorized") {

                //取消公众号/小程序授权

                $array_b = $xml->getElementsByTagName("AuthorizerAppid");

                $AuthorizerAppid = $array_b->item(0)->nodeValue;    //公众号/小程序appid

                $where = array("type" => 1, "appid" => $AuthorizerAppid);

                $save = array("authorizer_access_token" => "", "authorizer_refresh_token" => "", "authorizer_expires" => 0);

                //Db::name("wxuser")->where($where)->update($save);   //公众号取消授权

                Db::name("wxminiprograms")->where('authorizer_appid',$AuthorizerAppid)->update($save);   //小程序取消授权
                Db::name("deploy")->where('app_id',$AuthorizerAppid)->update(['appid'=>'']);   //小程序取消授权

            } else if ($infoType == "component_verify_ticket") {

                //微信官方推送的ticket值

                $array_e = $xml->getElementsByTagName("ComponentVerifyTicket");

                $component_verify_ticket = $array_e->item(0)->nodeValue;

                file_put_contents('ticket.log',$component_verify_ticket);

                if (model("weixin_account")->where(array("type" => 1))->update(array("component_verify_ticket" => $component_verify_ticket, "date_time" => time()))) {

                    echo "success";

                }

            }

        }

    }

    /*

        * 更新component_access_token

        * @params string $component_verify_ticket

        * */

    private function updateAccessToken()

    {

        $weixin_account = Db::name('weixin_account')->where(['type'=>1])->field('id,appId,appSecret,component_access_token,token_expires,component_verify_ticket')->find();

        if($weixin_account['token_expires'] <= time() ) {

            $apiUrl = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';

            $data = '{"component_appid":"'.$weixin_account['appId'].'" ,"component_appsecret": "'.$weixin_account['appSecret'].'","component_verify_ticket": "'.$weixin_account->component_verify_ticket.'"}';

            $json = json_decode(https_post($apiUrl,$data));

            if(isset($json->component_access_token)) {

                Db::name('weixin_account')->where(['id'=>$weixin_account['id']])->update(['component_access_token'=>$json->component_access_token,'token_expires'=>time()+7200]);

                return $json->component_access_token;
            }
        }
        return $weixin_account['component_access_token'];

    }

}